//
//  MCRecipeSearchHistoryManager.m
//  eCook_sub
//
//  Created by 萝卜头 on 2017/5/11.
//  Copyright © 2017年 Hangzhou Mo Chu Technology Co., Ltd. All rights reserved.
//

#import "MCRecipeSearchHistoryManager.h"
#import "YYCache.h"

static NSString * const kRecipeSearchHistoryKey = @"kRecipeSearchHistoryKey";

@implementation MCRecipeSearchHistoryManager

+ (YYCache *)sharedRecipeSearchHistoryCache {
    static YYCache *cache = nil;
    static dispatch_once_t onceToken;
    NSString *document=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    dispatch_once(&onceToken, ^{
        NSString *cachePath = [document stringByAppendingPathComponent:@"recipeSearchHistory"];
        cache = [[YYCache alloc] initWithPath:cachePath];
        cache.memoryCache.shouldRemoveAllObjectsOnMemoryWarning = YES;
        cache.memoryCache.shouldRemoveAllObjectsWhenEnteringBackground = NO;
    });
    return cache;
}

+ (instancetype)sharedInstance {
    static MCRecipeSearchHistoryManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[MCRecipeSearchHistoryManager alloc] init];
    });
    return manager;
}

#pragma mark - 增-改

- (void)addObject:(NSString *)object {
    NSMutableArray *array = [NSMutableArray arrayWithArray:[self allObject]];
    if (![array containsObject:object]) {
        [array insertObject:object atIndex:0];
        if (array.count >= 10) {
            array = (NSMutableArray *)[array subarrayWithRange:NSMakeRange(0, 9)];
        }
        [[MCRecipeSearchHistoryManager sharedRecipeSearchHistoryCache] setObject:array forKey:kRecipeSearchHistoryKey];
    }
}

#pragma mark - 查

- (NSArray *)allObject {
    return (NSArray *)[[MCRecipeSearchHistoryManager sharedRecipeSearchHistoryCache] objectForKey:kRecipeSearchHistoryKey];
}

- (BOOL)containsObject:(NSString *)object {
    return [[self allObject] containsObject:object];
}

#pragma mark - 删

- (void)removeAllObject {
    [[MCRecipeSearchHistoryManager sharedRecipeSearchHistoryCache] removeAllObjects];
}

- (void)removeObject:(NSString *)object {
    if ([[self allObject] containsObject:object]) {
        NSMutableArray *array = [NSMutableArray arrayWithArray:[self allObject]];
        [array removeObject:object];
        [[MCRecipeSearchHistoryManager sharedRecipeSearchHistoryCache] setObject:array forKey:kRecipeSearchHistoryKey];
    }
}

@end
